<script setup lang="ts">
import { useField } from 'vee-validate'

interface Props {
  /** 奖金id，-1表示晋级奖金，无值表示累计奖金 */
  vipBonusId?: string
  /** 奖金类型 */
  bonusType?: string
  /** 币种 */
  currencyId?: CurrencyCode | any
}
defineOptions({
  name: 'AppGetVipBonus',
})
const props = defineProps<Props>()
const emits = defineEmits(['closePop'])
definePageMeta({
  layout: 'other',
})

const isPop = ref(false)
const amountMax = ref(application.formatNumDecimal(0, currencyConfig.USDT.decimal))
const activeCurrency = ref(getCurrencyConfigByCode(props.currencyId ?? '706'))// ref(currencyConfig[currentGlobalCurrency.value])
const typeVal = ref('vip')
const options = ref([
  { label: $t('finance_other_tab_all'), value: 'vip' },
])
const {
  value: amount,
  setValue: setAmount,
  resetField: resetAmount,
  errorMessage: amountMsg,
  validate: valiAmount,
} = useField<string>('amount', (value) => {
  if (!value)
    return $t('input_amount')
  else if (Number(value) === 0)
    return $t('validate_deposit_amount_zero')
  else if (Number(value) < 0)
    return $t('validate_deposit_amount_pos')
  else if (value && Number(value) > Number(amountMax.value))
    return $t('validate_deposit_amount_max')
  return ''
}, { initialValue: '0.00' })
const {
  runAsync: runAsyncVipBonusApply,
  loading: loadVipBonusApply,
} = useRequest(ApiMemberVipBonusApply)

const { run: runVipBonusApplyAll, loading: loadApplyAll } = useRequest(ApiMemberVipBonusApplyAll, {
  onSuccess() {
    emits('closePop')
  },
})
const { runAsync: runAsyncGetPromoBonus, data: lvPromoBonus, loading: loadLvPromoBonus }
  = useRequest(ApiMemberVipBonusAvailable, {
    onSuccess(data) {
      if (props.vipBonusId) { // 处理晋级奖金
        options.value = data?.map((item) => {
          return {
            label: `VIP${item.vip}`,
            value: item.id,
            // ...item,
          }
        }) ?? []
        options.value.unshift({ label: $t('vip_promotion_bonus'), value: '-1' })
        if (props.vipBonusId) // 第一次打开是全部，需要从新计算金额
          selectTypeChange('-1')
      }
      else { // 处理累积奖金
        const item = (data && data?.length) ? data[0] : null
        if (!item || item.state === 2) {
          amountMax.value = application.formatNumDecimal(0, currencyConfig.USDT.decimal)
          setAmount(amountMax.value, false)
        }
        else {
          let amount = 0
          if (typeVal.value === 'vip') { //  累积奖金全部领取
            amount = Number(data)
          }
          else {
            amount = Number(sub(Number(item.amount), Number(item.receive_amount)))
          }
          amountMax.value = application.formatNumDecimal(amount, currencyConfig.USDT.decimal)
          setAmount(amountMax.value)
        }
      }
    },
  })
const { runAsync: runAsyncVipPrizeConfig } = useRequest(ApiMemberVipPrizeConfig, {
  onSuccess(data) {
    if (data) {
      const nav = data.nav
      const _options: {
        [t: string]: { label: string, value: string }
      } = {
        819: { label: $t('vip_day_salary_bonus'), value: '819' },
        820: { label: $t('vip_week_salary_bonus'), value: '820' },
        821: { label: $t('vip_month_salary_bonus'), value: '821' },
      }
      for (const key in nav) {
        if (nav[key] && _options[key])
          options.value.push(_options[key])
      }
    }
  },
})
const isLoading = computed(() => loadApplyAll.value || loadLvPromoBonus.value || loadVipBonusApply.value)
const dealOptions = computed(() => {
  if (props.vipBonusId)
    return
  return options.value.map((item) => {
    return {
      label: activeCurrency.value.name,
      desc: item.label,
      value: item.value,
    }
  })
})
const dealName = computed(() => {
  if (props.vipBonusId)
    return
  return options.value.filter(item => item.value == typeVal.value)[0].label
})

// 奖金类型切换
function selectTypeChange(val: string) {
  typeVal.value = val
  if (props.vipBonusId) { // 晋级奖金
    let amount = 0
    if (val !== '-1') {
      const item = lvPromoBonus.value?.find(t => t.id === val)
      amount = Number(sub(Number(item?.amount), Number(item?.receive_amount)))
    }
    else { // 全部领取
      amount = lvPromoBonus.value?.reduce((total, item) => Number(add(total, Number(sub(Number(item.amount), Number(item.receive_amount))))), 0) ?? 0
    }
    amountMax.value = application.formatNumDecimal(amount, currencyConfig.USDT.decimal)
    resetAmount()
    setAmount(amountMax.value, false)
  }
  else { // 日周月奖金
    runAsyncGetPromoBonus(typeVal.value === 'vip'
      ? ({
          flag: 'vip',
          cur: activeCurrency.value.cur,
        })
      : ({
          cash_type: typeVal.value,
          cur: activeCurrency.value.cur,
        }))
  }
}

async function submitBonus() {
  await valiAmount()
  if (!amountMsg.value) {
    if (typeVal.value !== '-1') {
      if (typeVal.value === 'vip') { // 累积奖金全部领取
        runVipBonusApplyAll({ cur: activeCurrency.value?.cur ?? '', flag: '' })
      }
      else {
        runAsyncVipBonusApply({
          id: props.vipBonusId ? typeVal.value : ((lvPromoBonus.value && lvPromoBonus.value[0].id) ?? ''),
          cur: activeCurrency.value?.cur ?? '',
          amount: amount.value,
        }).then(() => {
          emits('closePop')
        })
      }
    }
    else { // 晋级奖金全部领取
      runVipBonusApplyAll({ cur: activeCurrency.value?.cur ?? '', flag: 'upgrade' })
    }
  }
  else { // 金额为0提示
    message.error($t('currently_no_have_bonus_claim'))
  }
}

application.allSettled(
  [props.vipBonusId ? new Promise((resolve) => { resolve(true) }) : runAsyncVipPrizeConfig({ cur: activeCurrency.value.cur }), runAsyncGetPromoBonus(props.vipBonusId === '-1'
    ? ({ cash_type: props.bonusType ?? typeVal.value, cur: activeCurrency.value.cur })
    : ({ flag: 'vip', cur: activeCurrency.value.cur }))],
)
</script>

<template>
  <div>
    <div class="font-semibold text-[#B3BEC1] mb-1">
      {{ $t('active_bonus') }}
    </div>
    <div>
      <BaseInput name="bonus" :model-value="amount" disabled class="bonus-input mb-4">
        <template #right-icon>
          <BaseButton v-if="vipBonusId" type="none" class="bg-[#3A4142] text-xs h-8 font-semibold" @click.stop>
            <AppCurrencyIcon :currency-type="activeCurrency.name" class="size-3.5 mr-1" />
            {{ $t('vip_promotion_bonus') }}
          </BaseButton>
          <BaseButton v-else type="none" class="bg-[#3A4142] text-xs h-8 font-semibold" @click.stop="isPop = true">
            <AppCurrencyIcon :currency-type="activeCurrency.name" class="size-3.5 mr-1" />
            <span class="mx-2">{{ dealName }}</span>
            <BaseIcon name="uni-arrow-down" class="text-xs" style="--tg-base-icon-color: white" />
          </BaseButton>
        </template>
      </BaseInput>
    </div>
    <BaseButton class="w-full text-xs font-semibold" :loading="isLoading" @click="submitBonus">
      {{ $t('getBonus') }}
    </BaseButton>
    <BaseBob v-model:show="isPop" :option="dealOptions" :header="$t('choice_type')" :selected="typeVal" @update:selected="selectTypeChange">
      <template #label="{ label }">
        <AppCurrencyIcon :currency-type="label as EnumCurrencyKey" class="size-5 mr-2" />
      </template>
    </BaseBob>
  </div>
</template>

<style scoped lang="scss">
.bonus-input{
  --bc-input-pd-right: 0.2rem;
}
</style>
